#encoding=utf-8
from __future__ import division
import requests,captcha,sys,time,datetime,random,os
from django.shortcuts import render_to_response, HttpResponse, HttpResponseRedirect
from captcha.models import CaptchaStore
from captcha.helpers import captcha_image_url
import webconfig

#刷新验证码
def refreshCaptcha(request):
    #print '--refreshCaptcha---',request.META["QUERY_STRING"]
    if request.GET.get('newsn')=='1':
        csn=CaptchaStore.generate_key()
        cimageurl=captcha_image_url(csn)
        #print('---33333---')
        return HttpResponse(cimageurl)

#获取？后的数据，解密123456,天天猎人的
IsBase64=False
Base64Key=1234567890
import  base64,json
def Decode_OSS(t_strs,_interface=""):
    '''if _interface == "":
        return json.loads(t_strs)'''
    #return json.loads(t_strs)

    t_key = Base64Key
    t_cut = len(t_strs) - (t_key%len(t_strs))
    #print t_strs[0:t_cut]+t_strs[t_cut:]
    t_strs = base64.urlsafe_b64decode(t_strs[t_cut:]+t_strs[0:t_cut])
    #print t_strs,'---t_cut----',t_cut
    try:
        t_ret = json.loads(t_strs)
    except:
        assert False,t_strs

    return t_ret

def Decode_Request(_request):
    if IsBase64:
        t_query=_request.META["QUERY_STRING"]
        return Decode_OSS(t_query)
    return  _request.GET.dict()


APP_KEY='nhmj_@12345'
import hashlib
#数字签名验证uid=xxx&gameid=xxx&sign=xxxx
def get_sorted_kv_list(param):
    sorted_keys = sorted(param)
    return [(k, param[k]) for k in sorted_keys]
def get_sign(param, ignore_keys=('sign'), app_key=APP_KEY):
    param = {k: str(v) for k, v in param.items() if k not in ignore_keys}
    kv_list = get_sorted_kv_list(param)
    string = "".join(["&".join(["=".join(x) for x in kv_list]), app_key])
    return hashlib.md5(string).hexdigest()

#麻将的参数获取
IS_SIGN=False
def Decode_Request_MJ(_request,_sign=False):
    # print _request
    # print _request.get_host()      #获取请求地址
    # print _request.path                #获取请求的path，不带参数
    # print _request.get_full_path()  #获取完整参数
    t_obj=_request.GET.dict()

    if(IS_SIGN) or _sign:
        init_sign=t_obj['sign']
        encode_parms=get_sign(t_obj)
        #print(init_sign,'--Decode_Request_MJ---',encode_parms)
        if(init_sign!=encode_parms):
            t_obj={}
            t_obj['err reqest']=encode_parms

    t_obj['req_url']=_request.META[ 'PATH_INFO']
    return t_obj


import platform
def is_windows():
    cur_sys=platform.system().lower()
    return cur_sys.find('windows')>-1

#写日志
def add_log(_txt,_front='',_fname=''):
    from datetime import datetime as dt
    t_date=dt.strftime(dt.now(),'%Y-%m-%d')
    t_hour=dt.strftime(dt.now(),'%H')
    #文件是否存在os.path.dirname(__file__)
    if not is_windows():
        t_path = '/data/managerlog/' + t_date
    else:
        t_path=sys.path[0]+'/log/'+t_date
    t_txt=t_path+'/'+_fname+t_hour+'.txt'
    #print '--t_txt--',t_txt
    #if not os.path.exists(t_txt):
    #    os.mknod(t_txt)
    file_object=None
    try:
        if not os.path.exists(t_path):
            os.makedirs(t_path)
        file_object = open(t_txt, 'a')
        tt_time=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
        file_object.write(tt_time+'...'+_front+',,'+str(_txt)+'\n')
    except:
        pass
    finally:
        if file_object:
            file_object.close()

#错误的日志
def add_log_err(_txt):
    add_log(_txt,'error','err_')

#获取X天前的时间
def GetTime_ByNow(_day=-3):
    now=datetime.datetime.now()
    delta=datetime.timedelta(days=_day)
    n_days=now+delta
    return  n_days

def GetRandom(_len=6):
    _start='1'+'0'*(_len-1)
    _end='9'*_len
    _rnd=random.randint(int(_start),int(_end))
    return _rnd

#时间戳转换成时间
#x = time.localtime(1495175956)
def StampToTime(_times):
    x = time.localtime(_times)
    return time.strftime('%Y-%m-%d %H:%M:%S',x)

#时间转换时间戳
def TimeToStamp(_times):
    #a = "2017-09-28 10:00:00"
    return time.mktime(time.strptime(_times,'%Y-%m-%d %H:%M:%S'))

#datetime转时间戳
def DateTimeToStamp(_dtime):
    if type(_dtime)==datetime.datetime:
        return time.mktime(_dtime.timetuple())
    return time.time()

def datetime_offset_by_month(datetime1, n = 1):

    # create a shortcut object for one day
    one_day = datetime.timedelta(days = 1)

    # first use div and mod to determine year cycle
    q,r = divmod(datetime1.month + n, 12)

    # create a datetime2
    # to be the last day of the target month
    datetime2 = datetime.datetime(
        datetime1.year + q, r + 1, 1) - one_day

    '''
       if input date is the last day of this month
       then the output date should also be the last
       day of the target month, although the day
       www.iplaypy.com
       may be different.
       for example:
       datetime1 = 8.31
       datetime2 = 9.30
    '''
    if (datetime1.month!=(datetime1 + one_day).month):
        return datetime2

    '''
        if datetime1 day is bigger than last day of
        target month, then, use datetime2
        for example:
        datetime1 = 10.31
        datetime2 = 11.30
    '''

    if datetime1.day >= datetime2.day:
        return datetime2

    '''
     then, here, we just replace datetime2's day
     with the same of datetime1, that's ok.
    '''

    return datetime2.replace(day = datetime1.day)

#datetime转时间戳
def DateTimeToTimetuple(_time):
    if not _time:
        return -1
    return time.mktime(_time.timetuple())

#头像图片
def GetImgURL(_request,_url):
    #print _request,'---GetImgURL---'
    if _url.find('http:')>-1:
        return _url
    t_path="http://"+_request.META['HTTP_HOST']+"/"+_url
    t_path=webconfig.MANAGER_URL+_url
    return t_path

#获取ip
def GetIP(_request):
    tip=_request.META["REMOTE_ADDR"]
    if(tip.find(',')>0):
        tip=tip[0:tip.find(',')]
    return tip
